<template>
  <view class="work-page">
    <!-- <view class="temperature">
      <view class="text"> 当前温度°C </view>
      <view class="input">
        <input
          inputmode="decimal"
          @focus="currentFocus = -1"
          :selection-start="0"
          :selection-end="10000"
          v-model="workMainData.real_temperature"
          placeholder="请输入当前温度"
        />
      </view>
      <view class="text"> 当前湿度% </view>
      <view class="input">
        <input
          inputmode="decimal"
          @focus="currentFocus = -1"
          :selection-start="0"
          :selection-end="10000"
          v-model="workMainData.real_humidity"
          placeholder="请输入当前湿度"
        />
      </view>
    </view> -->
    <view class="info">
      <view class="tork_range" :style="`opacity: ${valToWrench ? 1 : 0}`"
        >扳手使用范围：{{ tork_range.min_tork }}~{{ tork_range.max_tork }}</view
      >
      <button
        class="startWork"
        @click="onStartWork"
        v-if="valToWrench && worktoolStore.deviceId.currDeviceId !== ''"
      >
        开始操作
      </button>
      <view class="unit">扭力单位：{{ worksubData[0]?.value_unit }}</view>
    </view>
    <uni-table border stripe emptyText="暂无更多数据">
      <uni-tr>
        <uni-th align="center" width="80px">组/位置</uni-th>
        <uni-th align="center" width="80px">实际值</uni-th>
        <uni-th align="center" width="50px">目标值</uni-th>
        <uni-th align="center" width="80px">笵围</uni-th>
      </uni-tr>
      <!-- 表格数据行 -->
      <uni-tr v-for="(item, index) in worksubData" :key="item.id">
        <uni-td align="center">{{ item.grp }}/{{ item.position_id[1] }}</uni-td>
        <uni-td align="center" :class="{ active: item.no_pass }">
          <input
            :disabled="!worktoolStore.deviceId.currDeviceId || users.includes(currentUser[0])"
            :value="item.decimal ? item.real_value : item.real_value2"
            :inputmode="currInputMode"
            placeholder="请输入"
            :focus="currentFocus === item.id"
            :selection-start="0"
            :selection-end="10000"
            @focus="inputFocus(item, index)"
            @confirm="onConfirm(item, index)"
            @input="
              (e) => {
                let eValue = Number(e.detail.value)
                item.decimal ? (item.real_value = eValue) : (item.real_value2 = eValue)
              }
            "
            @blur="onBlur(item, index)"
          />
        </uni-td>
        <uni-td align="center">
          <view v-if="item.target_value != 0 || item.target_value2 != 0">
            {{ item.decimal ? item.target_value.toFixed(3) : item.target_value2.toFixed(2) }}</view
          >
        </uni-td>
        <uni-td align="center">
          <view
            v-if="item.worktype_selection === 'A1M'"
            :class="{ minmaxvalue: valToWrench, active: !valToWrench }"
            >{{
              item.decimal
                ? item.min_value.toFixed(3) + '~' + item.max_value.toFixed(3)
                : item.min_value2.toFixed(2) + '~' + item.max_value2.toFixed(2)
            }}</view
          >
          <view v-if="item.worktype_selection === 'A2M'" :class="{ minmaxvalue: valToWrench }"
            >{{
              item.decimal
                ? item.min_angle.toFixed(3) + '~' + item.max_angle.toFixed(3)
                : item.min_angle2.toFixed(2) + '~' + item.max_angle2.toFixed(2)
            }}角度</view
          >
        </uni-td>
      </uni-tr>
    </uni-table>
  </view>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
//下面与template没有关系的脚本部分
import { useWorkmainStore, useWorksubStore, useWorktoolStore, useUserStore } from '@/stores'
import { dateShow, onceEvent } from '@/utils/utils.js'
import { emitter } from '@/EventBus'
//解决eval安全报错问题
import { bluetooth } from '@/utils/bluetooth.js'
import { pause } from 'wot-design-uni/components/common/util.ts'
const workMain = useWorkmainStore()
const worksubStore = useWorksubStore()
const worktoolStore = useWorktoolStore()
const userStore = useUserStore()
// const props = defineProps({
//   currentUser: Array,
// })
// // worksub数据
const worksubData = ref([])
// 当前work-main数据
const workMainData = ref({})
const workMainId = ref()
//当前用户
const currentUser = ref([])
//可放行的用户
const users = ref([])
// 当前聚焦框
const currentFocus = ref(-1)
//将worksub数据映射成操作蓝牙的数据格式，以便下发
let sendData = []
//扭矩下发的标记
const valToWrench = ref(false)
//扳手上下限值
const tork_range = ref({})
let tork_unit = ''
function onBlur(item, index) {
  // console.log('item,index', [item, index])
  let real_val = Number(item.real_value)
  let real_val2 = Number(item.real_value2)
  item.decimal ? (item.real_value = real_val.toFixed(3)) : (item.real_value2 = real_val2.toFixed(2))
  item.datetime_work = dateShow()[0]
  item.datetimeUTC = dateShow()[1]
  item.operator_id = currentUser.value[0]
  item.deviceId = worktoolStore.deviceId.currDeviceId
  //如果有范围值max_value,则判断,对于非计算的数据行
  if (item.max_value != 0 || item.max_value2 != 0) {
    if (item.decimal) {
      if (item.real_value < item.min_value || item.real_value > item.max_value) {
        item.no_pass = true
      } else {
        item.no_pass = false
      }
    } else {
      if (item.real_value2 < item.min_value2 || item.real_value2 > item.max_value2) {
        item.no_pass = true
      } else {
        item.no_pass = false
      }
    }
  } else {
    item.no_pass = false
  }
  // updateMainNopass()
}
//光标移到下一个输入框
function onConfirm(item) {
  // console.log('item,index', [item, index])
  let itemid = item.id
  let i = worksubData.value.map((itm) => itm.id).indexOf(itemid)
  if (i < worksubData.value.length - 1) {
    currentFocus.value = worksubData.value[i + 1]?.id
  }
}
const focusData = ref(null)
// 聚焦变化时事件
function inputFocus(item, index) {
  // console.log('inMode', currInputMode.value)
  currentFocus.value = item.id
  focusData.value = [item, index]
}

//worksub.no_pass 更新workmain.no_pass,以便判断是否操作完，并且符合数据范围，可以上传
function updateMainNopass() {
  // console.log('updateMainNopass')
  // console.log(workMainData.value)
  workMainData.value.no_pass = !worksubData.value.every((element) => {
    return !element.no_pass
  })
  // console.log(workMainData.value.no_pass)
}
// onShow(async () => {
//   //获取当前登录用户
//   // currentUser.value = [userStore.userInfo.uid, userStore.userInfo.name]
//   //获取可放行用户
//   // users.value = userStore.userInfo.users
//   // console.log(users.value)
//   // 初始化数据
//   initProces()
// })
onMounted(async () => {
  // emitter.on('onClickBlue', onClickBlue)
  // emitter.on('process', processBleData)
  emitter.on('onSendData', onSendData)
  currentUser.value = [userStore.userInfo.uid, userStore.userInfo.name]
  //获取可放行用户
  users.value = userStore.userInfo.users
  initProces()
})
function initProces() {
  //获取worksubData
  workMainId.value = worksubStore.currentWorkMainId
  worksubData.value = worksubStore.records[workMainId.value]
  //获取workMainData
  const workMainIndex = workMain.records.findIndex((item) => item.id == workMainId.value)
  workMainData.value = workMain.records[workMainIndex]
  // deviceId.value = worktoolStore.deviceId
  // console.log(workMainData.value)
  console.log(worksubData.value)
  if (worksubData.value.length > 10) {
    worksubData.value.splice(10, worksubData.value.length - 10)
  }
  tork_unit = worksubData.value[0].value_unit
  console.log('tork_unit', tork_unit)
  // let { worktype, target_tork, max_tork, min_tork, angle, max_angle, min_angle } = sendData
  sendData = worksubData.value.map((item, index) => {
    return {
      id: item.id,
      name: item.number,
      worktype: item.worktype_selection + index,
      target_tork: item.decimal
        ? parseFloat(item.target_value.toFixed(3))
        : parseFloat(item.target_value2.toFixed(2)),
      max_tork: item.decimal
        ? parseFloat(item.max_value.toFixed(3))
        : parseFloat(item.max_value2.toFixed(2)),
      min_tork: item.decimal
        ? parseFloat(item.min_value.toFixed(3))
        : parseFloat(item.min_value2.toFixed(2)),
      max_angle: item.decimal
        ? parseFloat(item.max_angle.toFixed(3))
        : parseFloat(item.max_angle2.toFixed(2)),
      min_angle: item.decimal
        ? parseFloat(item.min_angle.toFixed(3))
        : parseFloat(item.min_angle2.toFixed(2)),
    }
  })
  console.log('sendData', sendData)
}
onUnmounted(() => {
  //关闭WorkHead所发出的事件
  // emitter.off('onClickBlue', onClickBlue)
  emitter.off('process')
  emitter.off('onSendData')
  updateMainNopass()
})
//input组件inputmode，判断是否跳出软键盘
const currInputMode = computed(() => {
  if (!worktoolStore.notBluedev) {
    console.log('none')
    return 'none'
  } else {
    console.log('decimal')
    return 'decimal'
  }
})
//选中蓝牙后，进行创建连接并采集数据
// function onClickBlue(item) {
//   clickBlue(item, processBleData)
// }
async function onSendData() {
  // sendData(processBleData, currentFocus.value, currInputMode.value)
  if (workMainData.value.temp === '3') {
    const opts = worktoolStore.opts
    // console.log('opts', opts)
    //获取扳手上下限值
    const cmd = getApp().globalData.protosUtils.cmd.getCmd('critical')
    // console.log('cmd', cmd)
    await bluetooth.writeValue(opts, cmd)
    const data = await onceEvent(uni.$myNotifyEventName)
    const readRes = getApp().globalData.protosUtils.readDeviceCriticalValue(data)
    tork_range.value = readRes
    console.log('tork_range', tork_range.value)
    // uni.$once(uni.$myNotifyEventName, (data) => {
    //   const readRes = getApp().globalData.protosUtils.readDeviceCriticalValue(data)
    //   // console.log('readRes:', readRes)
    //   tork_range.value = readRes
    //   console.log('tork_range', tork_range.value)
    // })
    // await pause(500)
    for (let s of sendData) {
      console.log('s', s)
      if (s.min_tork < tork_range.value.min_tork || s.max_tork > tork_range.value.max_tork) {
        uni.showToast({ title: '扭矩超出扳手范围', icon: 'error' })
        return
      }
    }
    //先设置扭力单位
    const cmdUnit = getApp().globalData.protosUtils.cmd.getUnitCmd(tork_unit)
    // console.log('cmdUnit', cmdUnit)
    await bluetooth.writeValue(opts, cmdUnit)
    await pause(500)

    //开始下发工单的扭矩要求
    const orderList = JSON.parse(JSON.stringify(sendData))
    if (!orderList.length) {
      uni.showToast({ title: '无工单数据', icon: 'error' })
      return
    }
    // orders.value = JSON.parse(JSON.stringify(orderArr))
    uni.showLoading({
      title: '执行中...',
      mask: true,
    })

    // 下发工单
    const cmdArr = getApp().globalData.protosUtils.cmd.getSendOrderBatchCmd(sendData) // 指令数组
    console.log('cmdArr', cmdArr)
    for (let i = 0; i < cmdArr.length; i++) {
      // await processBLE.sendToDevice(opts.write, cmdArr[i])
      await bluetooth.writeValue(opts, cmdArr[i])
      // 暂停0.5秒
      await pause(500)
    }
    uni.hideLoading()
    uni.showToast({ title: '下发成功' })
    valToWrench.value = true
  }
}

// 心跳定时器
let heartbeatTimer = null
let num = 0
// 提示框标题前缀
let loadingTitlePrefix = ''
// 加载框标题 -单个工单完成
let finishLoadingTitle = '请准备'
// 开始操作
async function onStartWork() {
  currentFocus.value = worksubData.value[0].id
  const opts = worktoolStore.opts
  //   console.log('currentFocus', currentFocus.value)
  // isWork.value = false

  for (let order of sendData) {
    // const order = orders.value[0]
    console.log('order', order)
    // 设置模式
    uni.showLoading({
      title: finishLoadingTitle,
      mask: true,
    })
    const cmd = getApp().globalData.protosUtils.cmd.setModeCmd(order)
    await bluetooth.writeValue(opts, cmd)
    await pause(500)
    for (let j = 0; j < 1000; j++) {
      uni.showLoading({
        title: loadingTitlePrefix + order.name.split('@')[0] + '执行中...',
        mask: true,
      })
      //触发心跳获取数据
      const maxItem = await getData(order)
      // console.log('找到的最大tork值为:' + j, maxItem)
      if (maxItem) {
        if (maxItem.max_tork < order.min_tork || maxItem.max_tork > order.max_tork) {
          loadingTitlePrefix = '重做->'
          // continue
        } else {
          worksubData.value.forEach((item, index) => {
            if (item.id == order.id) {
              if (item.decimal) {
                item.real_value = maxItem.max_tork
              } else {
                item.real_value2 = maxItem.max_tork
              }
            }
          })
          onConfirm(order)
          // currentFocus.value = order.id + 1
          // saveSendData(maxItem, order)
          // console.log('保存数据:' + JSON.stringify(maxItem))
          loadingTitlePrefix = ''
          finishLoadingTitle = order.name.split('@')[0] + '完成'
          break
        }
      }
    }
    uni.hideLoading()
  }
  clearInterval(heartbeatTimer)
  // wx.offBLECharacteristicValueChange() // 只有微信

  // models.value = sendData.value[0].name.split('@')[1] + '全部操作完成'
  uni.showToast({
    title: sendData[0].name.split('@')[1] + '全部操作完成！',
    icon: 'none',
  })
  // sendData.value = []
  finishLoadingTitle = '请准备'
}
// 获取数据
async function getData(item) {
  if (!item) {
    throw new Error('工单内容不能为空')
    // return
  }
  const opts = worktoolStore.opts
  function setIntervalImmediate(func, delay, ...args) {
    // 立即执行一次
    func.apply(null, args)
    // 返回 setInterval 的 ID 以便后续清除
    return setInterval(func, delay, ...args)
  }
  // 发送心跳，读取数据
  function sendHeartbeat() {
    clearInterval(heartbeatTimer)
    heartbeatTimer = setIntervalImmediate(async () => {
      num++
      if (num == 1000) {
        clearInterval(heartbeatTimer)
        num = 0
      } else {
        const cmd = getApp().globalData.protosUtils.cmd.getCmd('heartbeat')
        await bluetooth.writeValue(opts, cmd)
        // await bluetoothTool.sendToDevice(opts.write, cmd)
      }
    }, 3000)
  }
  return new Promise((resolve, reject) => {
    const logRes = []
    loadingTitlePrefix = item.name.split('@')[0] + '执行中...'
    //发出心跳数据
    sendHeartbeat()
    // 开始监听来自于扳手的数据
    let tork_value = Math.round(item.min_tork * 10) / 100
    let min_tork = tork_value.toFixed(2)

    uni.$on(uni.$myNotifyEventName, (data) => {
      // console.log('data:', data)
      if (data.length === 0) {
        // sendHeartbeat()
        return
      }
      let logItem = getApp().globalData.protosUtils.formatDeviceData(data) //这里的cmdVal是readType=log的心跳数据
      let res = { max_tork: 0 }
      if (logItem.tork >= min_tork || (logItem.tork != null && logItem.max_tork >= min_tork)) {
        logRes.push(logItem)
        //当瞬时扳手数据小于最小值的10%，采集停止，然后求最大值即为扳手的peek峰值
      } else if (logItem.tork <= min_tork && logRes.length != 0) {
        clearInterval(heartbeatTimer)
        logRes.push(logItem)
        console.log('logRes:', logRes)
        // const maxTork = 0
        logRes.forEach((obj) => {
          if (obj.max_tork > res.max_tork) {
            // res = obj
            res.max_tork = obj.max_tork
          }
        })
        console.log('res:', res)

        uni.$off(uni.$myNotifyEventName)
        resolve(res)
        return
      }
    })
  })
}
//下面是采集数据后的处理，需要根据当前具体组件的内容重写
// function processBleData(getValue) {
//   let value = getValue[0]
//   let unit = getValue[1]
//   console.log('processBleData', value)
//   let item = focusData.value[0]
//   let index = focusData.value[1]
//   if (item.decimal) {
//     item.real_value = value.toFixed(3)
//     console.log('real_value', item.real_value)
//   } else {
//     item.real_value2 = value.toFixed(2)
//     console.log('real_value2', item.real_value2)
//   }
//   item.datetime_work = dateShow()[0]
//   item.datetimeUTC = dateShow()[1]
//   item.operator_id = currentUser.value[0]
//   item.deviceId = worktoolStore.deviceId.currDeviceId
//   if (item.decimal) {
//     if (item.real_value < item.min_value || item.real_value > item.max_value) {
//       item.no_pass = true
//     } else {
//       item.no_pass = false
//     }
//   } else {
//     if (item.real_value2 < item.min_value2 || item.real_value2 > item.max_value2) {
//       item.no_pass = true
//     } else {
//       item.no_pass = false
//     }
//   }
//   //updateMainNopass()
//   onConfirm(item, index)
// }
</script>

<style lang="scss" scoped>
.work-page {
  .margin-top-bottom {
    margin: 10px 0;
  }
  .minmaxvalue {
    color: darkgreen;
  }
  .info {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .tork_range {
    font-size: 10px;
    text-align: center;
    padding-left: 10px;
    line-height: 20px;
  }
  .unit {
    line-height: 20px;
    font-size: 10px;
    text-align: right;
    padding-right: 10px;
  }
  .startWork {
    height: 20px;
    line-height: 20px;
    font-size: 10px;
    background: #286aff;
    color: white;
  }
  // .temperature {
  //   display: flex;
  //   flex-direction: row;
  //   justify-content: center;
  //   width: 100%;
  //   .text {
  //     font-size: 12px;
  //     font-weight: 700;
  //     color: blueviolet;
  //     width: 70px;
  //   }
  //   .input {
  //     width: 30px;
  //   }
  // }
  .temperature {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center; // 添加垂直居中
    flex-wrap: wrap; // 允许换行
    width: 100%;
    gap: 10px; // 添加间距
    padding: 10px 0; // 添加上下内边距

    .text {
      font-size: 12px; // 增大字体
      font-weight: 700;
      color: blueviolet;
      white-space: nowrap; // 防止文字换行
    }

    .input {
      width: 50px; // 增加输入框宽度

      input {
        width: 100%;
        height: 36px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 0 8px;
        box-sizing: border-box;
        background-color: #fff;

        &:focus {
          border-color: #1598fa;
          outline: none;
        }
      }
    }
  }
  .conclude {
    margin-top: 5px;
    width: 100%;
    text-align: center;
    font-size: 14px;
  }
  .check {
    background-color: #e0ffff;
  }
  .header {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-bottom: 1px solid $border-color;
    &-prd_name {
      font-size: $text-font-size-m;
      color: $text-font-color-2;
    }
  }
  .active {
    color: #e64340;
  }
  .err-text {
    font-size: $text-font-size-s !important;
    color: $uni-color-error;
  }
  .photo {
    // width: 50px;
    // height: 70px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    // .icon {
    //   padding: 6px;
    //   background: #f0f0f0;
    //   :deep(.uni-icons) {
    //     font-size: 18px !important;
    //   }
    // }
    .button {
      display: flex;
      flex-direction: row;
      justify-items: center;
      &-photo {
        padding: 6px;
        font-size: $text-font-size-s;
        color: $button-color;
      }
      &-delete {
        @extend .button-photo;
        color: $button-err;
      }
    }
  }
  .button-all {
    color: $button-color;
  }
  // .signature {
  //   margin: 10px;
  // }
  .collect-data-popup {
    margin: 10px;
    min-height: 40vh;
    &-title {
      padding: 10px;
      display: flex;
      justify-content: space-between;
      font-weight: 700;
      border-bottom: 1px solid $border-color;
    }
    .add-data {
      padding: 10px;
      font-size: $text-font-size-m;
      color: $button-color;
    }
    .delete-data {
      color: $button-color;
    }
    &-bottom {
      display: block;
      margin: 14px 0;
      padding: 2px 0;
    }
  }
  .document_image {
    width: fit-content;
    margin: 20px auto;
  }
  .checked {
    //border: 1px solid $brand-theme-color;
    background: rgba(194, 219, 239, 0.2);
  }
}
</style>
